import {getUser} from '../user.js'
import { splitCamel, arrayToSql } from '../util/string.js'
import db from '../mysql.js'

const userTableAlias = 'user'
const userSelect = `select ${userTableAlias}.user_id userId, ${userTableAlias}.user_name userName, ${userTableAlias}.nick_name nickName, ${userTableAlias}.sex, ${userTableAlias}.email, ${userTableAlias}.phonenumber, ${userTableAlias}.qq, ${userTableAlias}.wx, ${userTableAlias}.id_card idCard, ${userTableAlias}.status, ${userTableAlias}.create_by createBy, ${userTableAlias}.create_time createTime, ${userTableAlias}.update_by updateBy, ${userTableAlias}.update_time updateTime, ${userTableAlias}.remark from sys_user ${userTableAlias} where ${userTableAlias}.del_flag = '0' `
const userSelectCount = `select count(*) as total from sys_user ${userTableAlias} where user.del_flag = '0' `

function addUserSqlWhereClause (sql, req) {
	let {sex, userName, nickName, email, phonenumber, qq, wx, idCard, status} = req.body
	// - 性别查询
	if (sex && sex.length > 0) {
		sql += ` and ${userTableAlias}.sex in (${arrayToSql(sex)})`
	}
	// - 状态查询
	if (status && status.length > 0) {
		sql += ` and ${userTableAlias}.status in (${arrayToSql(status)})`
	}
	// - 用户名查询
	if (userName && userName.length > 0) {
		sql += ` and ${userTableAlias}.user_name like '%${userName}%'`
	}
	// - 昵称查询
	if (nickName && nickName.length > 0) {
		sql += ` and ${userTableAlias}.nick_name like '%${nickName}%'`
	}
	// - 邮箱查询
	if (email && email.length > 0) {
		sql += ` and ${userTableAlias}.email = '${email}'`
	}
	// - 手机号查询
	if (phonenumber && phonenumber.length > 0) {
		sql += ` and ${userTableAlias}.phonenumber = '${phonenumber}'`
	}
	// - QQ号查询
	if (qq && qq.length > 0) {
		sql += ` and ${userTableAlias}.qq = '${qq}'`
	}
	// - 微信号查询
	if (wx && wx.length > 0) {
		sql += ` and ${userTableAlias}.wx = '${wx}'`
	}
	// - 身份证查询
	if (idCard && idCard.length > 0) {
		sql += ` and ${userTableAlias}.id_card = '${idCard}'`
	}
	return sql
}

function getOrderBys(req) {
	let {sortParams} = req.body
	let orderBys = []
	if (sortParams && sortParams.length > 0) {
		sortParams.sort((p1, p2) => p1.multiple - p2.multiple).forEach(p => {
			if (!p.order) {
				return
			}
			orderBys.push(`${userTableAlias}.${splitCamel(p.field).join('_')} ${p.order === 'ascend' ? 'ASC' : 'DESC'}`)
		});
	}
	return orderBys
}

export function getUserList(req, res) {
	console.log('getUserList - req', req.query, req.body)
	let {current = 1, pageSize = 10} = req.body
    getUser(req).then(user => {
		console.log('getUserList - getUser', user)
		// 拼接sql
		// 拼接查询条件
		let sql = addUserSqlWhereClause(userSelect, req)
		// 拼接order by
		let orderBys = getOrderBys(req)
		if(orderBys &&  orderBys.length > 0) {
			sql += ` order by ${orderBys.join(',')}`
		}
		// 拼接分页
		sql += ` limit ${(current - 1)*pageSize}, ${pageSize}`
		console.log('getUserList - sql', sql)
		db.query(sql, [], (err, result) => {
			console.log('getUserList - rows', err, result)
			let results = {data: {rows:[], total: 0}}
			if (err) {
				results.msg = 'query rows error：' + err;
				results.code = 500
			} else {
				results.code = 200
				results.data.rows = result;
				let sqlCount = addUserSqlWhereClause(userSelectCount, req)
				db.query(sqlCount, [], (errCount, resultCount) => {
					console.log('getUserList - total', errCount, resultCount)
					if (errCount) {
						results.msg = 'query total error：' + errCount;
						results.code = 500
					} else {
						results.data.total = resultCount[0].total;
						res.json(results)
					}
				})
			}
		})
	}).catch(err => {
		console.log(err)
		res.json(err)
	})
}